package cn.edu.gzasc.registration.controller;

import cn.edu.gzasc.registration.dto.ResponseDto;
import cn.edu.gzasc.registration.entity.User;
import cn.edu.gzasc.registration.repository.UserRepository;
import cn.edu.gzasc.registration.services.UserApiService;
import lombok.AllArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping(path="/api", produces = {MediaType.APPLICATION_JSON_VALUE})
@AllArgsConstructor
@Validated
@CrossOrigin
public class UserApiController {

    private UserRepository userRepository;
    private UserApiService userApiService;

    // 创建用户
    @PostMapping("/user")
    public ResponseEntity<User> createUser(@Validated @RequestBody User user) {
        // 保存新用户到数据库，包含性别和生日字段
        userRepository.save(user);
        return ResponseEntity.ok(user);
    }

    // 获取所有用户
    @GetMapping("/users")
    public ResponseEntity<List<User>> listAll() {
        return ResponseEntity.ok(userRepository.findAll());
    }

    // 根据ID获取用户
    @GetMapping("/users/{id}")
    public ResponseEntity<User> fetchUserById(@PathVariable int id) {
        Optional<User> user = userRepository.findById((long) id); // 使用 JPA 内置的 findById 方法
        return user.map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.notFound().build()); // 返回用户或 404
    }

    // 删除用户
    @DeleteMapping("/users/{id}")
    public ResponseEntity<ResponseDto> deleteUserById(@PathVariable int id) {
        userRepository.deleteById((long) id);
        return ResponseEntity.status(200).body(new ResponseDto("200", "success"));
    }

    // 更新用户信息
    @PutMapping("/users")
    public ResponseEntity<ResponseDto> updateUser(@Validated @RequestBody User user) {
        // 更新用户信息，保存包含性别和生日字段的用户
        userRepository.save(user);
        return ResponseEntity.ok(new ResponseDto("200", "success"));
    }

    // 根据用户ID查询用户（精确查询）
    @GetMapping("/users/search")
    public ResponseEntity<List<User>> searchUsersById(@RequestParam(required = false) Long id) {
        List<User> users;
        if (id != null) {
            // 根据ID精确查询用户
            Optional<User> user = userRepository.findById(id);
            users = user.map(List::of).orElse(List.of()); // 如果找到用户，放入列表；否则返回空列表
        } else {
            // 如果没有提供查询条件，返回所有用户
            users = userRepository.findAll();
        }
        return ResponseEntity.ok(users);
    }
}